<template>
  <div class="merchant-dashboard">
    <h2 class="page-title">商家管理面板</h2>
    
    <!-- 数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon"><i class="el-icon-shopping-cart-full"></i></div>
          <div class="card-data">
            <div class="data-number">{{ todayOrders }}</div>
            <div class="data-title">今日订单</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon"><i class="el-icon-money"></i></div>
          <div class="card-data">
            <div class="data-number">¥{{ todaySales.toFixed(2) }}</div>
            <div class="data-title">今日销售额</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon"><i class="el-icon-dish"></i></div>
          <div class="card-data">
            <div class="data-number">{{ totalFoods }}</div>
            <div class="data-title">菜品总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon"><i class="el-icon-star-on"></i></div>
          <div class="card-data">
            <div class="data-number">{{ rating.toFixed(1) }}</div>
            <div class="data-title">店铺评分</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 商家状态 -->
    <el-card class="status-card">
      <div class="card-header">
        <span>店铺状态</span>
        <el-switch
          v-model="businessStatus"
          active-text="营业中"
          inactive-text="休息中"
          @change="toggleBusinessStatus">
        </el-switch>
      </div>
      <div class="shop-info">
        <div class="info-item">
          <span class="label">店铺名称：</span>
          <span class="value">{{ merchantInfo.shopName }}</span>
        </div>
        <div class="info-item">
          <span class="label">营业时间：</span>
          <span class="value">{{ merchantInfo.businessHours }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系电话：</span>
          <span class="value">{{ merchantInfo.contactPhone }}</span>
        </div>
        <div class="info-item">
          <span class="label">店铺地址：</span>
          <span class="value">{{ merchantInfo.shopAddress }}</span>
        </div>
        <div class="info-item">
          <span class="label">月销量：</span>
          <span class="value">{{ merchantInfo.monthlySales }} 单</span>
        </div>
      </div>
    </el-card>
    
    <!-- 功能快捷入口 -->
    <h3 class="section-title">快捷功能</h3>
    <el-row :gutter="20" class="quick-actions">
      <el-col :span="6">
        <el-card shadow="hover" class="action-card" @click.native="$router.push('/merchant/orders')">
          <div class="card-icon"><i class="el-icon-s-order"></i></div>
          <div class="card-title">订单管理</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="action-card" @click.native="$router.push('/merchant/foods')">
          <div class="card-icon"><i class="el-icon-dish-1"></i></div>
          <div class="card-title">菜品管理</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="action-card" @click.native="$router.push('/merchant/profile')">
          <div class="card-icon"><i class="el-icon-s-shop"></i></div>
          <div class="card-title">店铺信息</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="action-card" @click.native="$router.push('/merchant/reviews')">
          <div class="card-icon"><i class="el-icon-chat-line-square"></i></div>
          <div class="card-title">评价管理</div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 待处理订单 -->
    <h3 class="section-title">待处理订单</h3>
    <el-card class="orders-card">
      <el-table :data="pendingOrders" stripe style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.totalPrice ? scope.row.totalPrice.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="primary" @click="handleOrder(scope.row)">处理</el-button> -->
            <el-button size="mini" type="info" @click="viewOrderDetail(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="view-more">
        <el-button type="text" @click="$router.push('/merchant/orders')">查看更多订单 <i class="el-icon-arrow-right"></i></el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { 
  getMerchantOrders, 
  updateOrderStatus, 
  getMerchantOrderStats, 
  acceptOrder, 
  deliverOrder, 
  completeOrderByMerchant 
} from '@/api/order'
import { getFoodCountByMerchant } from '@/api/food'
import { getMerchantByUserId, updateBusinessStatus } from '@/api/merchant'

export default {
  name: 'MerchantDashboard',
  data() {
    return {
      // 数据概览
      todayOrders: 0,
      todaySales: 0,
      totalFoods: 0,
      rating: 0,
      
      // 商家信息
      merchantInfo: {
        id: null,
        shopName: '',
        shopLogo: '',
        shopDesc: '',
        businessHours: '',
        contactPerson: '',
        contactPhone: '',
        shopAddress: '',
        status: 0,
        businessStatus: 0,
        rating: 0,
        monthlySales: 0
      },
      
      // 营业状态
      businessStatus: false,
      
      // 待处理订单
      pendingOrders: []
    }
  },
  created() {
    this.getMerchantInfo()
    this.getDashboardData()
    this.getPendingOrders()
  },
  methods: {
    // 获取商家信息
    getMerchantInfo() {
      const userId = this.$store.state.user.id
      getMerchantByUserId(userId)
        .then(response => {
          if (response.code == 200) {
            this.merchantInfo = response.data
            this.rating = this.merchantInfo.rating
            this.businessStatus = this.merchantInfo.businessStatus === 1
            // 获取到商家信息后再获取仪表盘数据
            this.getDashboardData()
            this.getPendingOrders()
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 获取仪表盘数据
    getDashboardData() {
      const merchantId = this.merchantInfo.id || this.$store.state.user.merchantId
      
      // 获取今日订单数量和销售额
      const today = new Date()
      // 格式化日期为 yyyy-MM-dd
      const dateStr = today.toISOString().split('T')[0]
      
      // 使用getMerchantOrderStats获取订单统计数据
      getMerchantOrderStats(merchantId, dateStr, dateStr)
        .then(response => {
          if (response.code == 200) {
            this.todayOrders = response.data.totalOrders || 0
            this.todaySales = response.data.totalSales || 0
          } else {
            console.error('获取订单统计失败:', response.data.message)
            this.$message.error(response.data.message || '获取订单统计失败')
          }
        })
        .catch(error => {
          console.error('获取订单统计失败:', error)
          if (error.response) {
            console.error('错误详情:', error.response.data)
            this.$message.error(error.response.data.message || '获取订单统计失败')
          } else {
            this.$message.error(error.message || '获取订单统计失败')
          }
        })
      
      // 获取菜品总数
      getFoodCountByMerchant(merchantId)
        .then(response => {
          if (response.code == 200) {
            this.totalFoods = response.data || 0
          }
        })
        .catch(error => {
          console.error('获取菜品数量失败', error)
        })
    },
    
    // 获取待处理订单
    getPendingOrders() {
      const merchantId = this.merchantInfo.id || this.$store.state.user.merchantId
      
      // 获取待接单和配送中的订单
      getMerchantOrders(merchantId, {
        page: 1,
        size: 5,
        status: 1 // 待接单状态
      })
        .then(response => {
          if (response.code == 200) {
            this.pendingOrders = response.data || []
            
            // 如果待接单的订单不足5个，获取配送中的订单
            if (this.pendingOrders.length < 5) {
              const remainingSize = 5 - this.pendingOrders.length
              
              getMerchantOrders(merchantId, {
                page: 1,
                size: remainingSize,
                status: 2 // 备餐中状态
              })
                .then(resp => {
                  if (resp.data.code === 200 && resp.data.data && resp.data.data.length > 0) {
                    this.pendingOrders = [...this.pendingOrders, ...resp.data.data]
                  }
                })
                .catch(error => {
                  console.error('获取备餐中订单失败', error)
                })
            }
          }
        })
        .catch(error => {
          console.error('获取待处理订单失败', error)
        })
    },
    
    // 切换营业状态
    toggleBusinessStatus(status) {
      const merchantId = this.merchantInfo.id
      const newStatus = status ? 1 : 0
      
      updateBusinessStatus(merchantId, newStatus)
        .then(response => {
          if (response.code == 200) {
            this.$message.success(status ? '已开始营业' : '已暂停营业')
          } else {
            this.businessStatus = !status // 切换失败，恢复状态
            this.$message.error(response.data.message || '切换营业状态失败')
          }
        })
        .catch(error => {
          console.error('切换营业状态失败', error)
          this.businessStatus = !status // 切换失败，恢复状态
          this.$message.error('切换营业状态失败')
        })
    },
    
    // 处理订单
    handleOrder(order) {
      if (order.status === 1) { // 待接单
        this.$confirm('确认接受该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 接受订单
          acceptOrder(order.id, this.merchantInfo.id)
            .then(response => {
              if (response.code == 200) {
                this.$message.success('已接受订单')
                this.getPendingOrders() // 刷新列表
              } else {
                this.$message.error(response.data.message || '操作失败')
              }
            })
            .catch(error => {
              console.error('接受订单失败', error)
              this.$message.error('接受订单失败')
            })
        }).catch(() => {
          // 取消操作
        })
      } else if (order.status === 2) { // 备餐中，开始配送
        this.$confirm('确认开始配送该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 开始配送
          deliverOrder(order.id, this.merchantInfo.id)
            .then(response => {
              if (response.code == 200) {
                this.$message.success('订单已开始配送')
                this.getPendingOrders() // 刷新列表
              } else {
                this.$message.error(response.data.message || '操作失败')
              }
            })
            .catch(error => {
              console.error('开始配送失败', error)
              this.$message.error('操作失败')
            })
        }).catch(() => {
          // 取消操作
        })
      } else if (order.status === 3) { // 配送中，标记完成
        this.$confirm('确认订单已送达并完成吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 完成订单
          completeOrderByMerchant(order.id, this.merchantInfo.id)
            .then(response => {
              if (response.code == 200) {
                this.$message.success('订单已完成')
                this.getPendingOrders() // 刷新列表
              } else {
                this.$message.error(response.data.message || '操作失败')
              }
            })
            .catch(error => {
              console.error('完成订单失败', error)
              this.$message.error('完成订单失败')
            })
        }).catch(() => {
          // 取消操作
        })
      }
    },
    
    // 查看订单详情
    viewOrderDetail(orderId) {
      this.$router.push(`/merchant/orders`)
    },
    
    // 获取状态类型
    getStatusType(status) {
      const types = {
        0: 'info',     // 待付款
        1: 'warning',  // 待接单
        2: 'primary',  // 备餐中
        3: 'success',  // 配送中
        4: 'info',     // 已完成
        5: 'danger'    // 已取消
      }
      return types[status] || 'info'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const texts = {
        0: '待付款',
        1: '待接单',
        2: '备餐中',
        3: '配送中',
        4: '已完成',
        5: '已取消'
      }
      return texts[status] || '未知状态'
    }
  }
}
</script>

<style scoped>
.merchant-dashboard {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 120px;
  display: flex;
  align-items: center;
  padding: 20px;
  color: #606266;
}

.card-icon {
  font-size: 40px;
  margin-right: 20px;
  color: #409EFF;
}

.card-data {
  flex: 1;
}

.data-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.data-title {
  font-size: 14px;
  color: #909399;
}

.status-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header span {
  font-size: 16px;
  font-weight: bold;
}

.shop-info {
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  width: 50%;
  margin-bottom: 10px;
}

.info-item .label {
  font-weight: bold;
  margin-right: 5px;
}

.section-title {
  margin: 20px 0 15px;
  font-size: 18px;
  font-weight: bold;
}

.action-card {
  height: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.action-card .card-icon {
  font-size: 36px;
  margin-bottom: 10px;
}

.action-card .card-title {
  font-size: 16px;
  font-weight: bold;
}

.orders-card {
  margin-bottom: 20px;
}

.view-more {
  margin-top: 15px;
  text-align: right;
}
</style> 